package com.huixuebao.after.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huixuebao.after.dto.PolicyGroupDTO;
import com.huixuebao.after.dto.SubmitPolicyGroupDTO;
import com.huixuebao.after.entity.*;
import com.huixuebao.after.mapper.*;
import com.huixuebao.after.service.PolicyOrderService;
import com.huixuebao.common.bean.ApiResult;
import com.huixuebao.common.enumeration.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;

@Slf4j
@Service
public class PolicyOrderServiceImpl implements PolicyOrderService {

    @Autowired
    PolicyOrderMapper policyOrderMapper;
    @Autowired
    UserInsureMapper userInsureMapper;
    @Autowired
    StudentMapper studentMapper;
    @Autowired
    MechanismMapper mechanismMapper;
    @Autowired
    CourseMapper courseMapper;
    @Override
    public ApiResult<List<PolicyGroupDTO>> postBackData(List<PolicyGroupDTO> list) {

        return null;
    }

    @Override
    public ApiResult submitGroupPolicy(SubmitPolicyGroupDTO submitPolicyGroupDTO) {
        ApiResult apiResult = new ApiResult();
        try{
            //订单号#
            String orderId = submitPolicyGroupDTO.getOrderId();
            //投保人姓名#
            String insuredName = submitPolicyGroupDTO.getInsuredName();
            //证件号#
            String cid = submitPolicyGroupDTO.getCid();
            //被保险人姓名(B_to公司名称)#
            String holderName = submitPolicyGroupDTO.getHolderName();
            //被保险人手机号
            String holderPhone = submitPolicyGroupDTO.getHolderPhone();
            //被保人证件号
            String holderCid = submitPolicyGroupDTO.getHolderCid();
            //学员姓名（非必录）
            String studentName = submitPolicyGroupDTO.getStudentName();
            //机构名称
            String mechanismName = submitPolicyGroupDTO.getMechanismName();
            //教育机构证件号码
            String businessLicens = submitPolicyGroupDTO.getBusinessLicens();
            //教育地点
            String address =submitPolicyGroupDTO.getAddress();
            //教育项目
            String courseProject = submitPolicyGroupDTO.getCourseProject();
            //保费#
            String premium = submitPolicyGroupDTO.getPremium();
            //实缴教育费用
            String reality = submitPolicyGroupDTO.getReality();
            //总保额#
            String totalPremium = submitPolicyGroupDTO.getTotalPremium();
            //教育合同文件地址集合（多个地址间用英文;分割）
            String businessLicensAddress = submitPolicyGroupDTO.getBusinessLicensAddress();
            //培训期间(开始时间)
            String startTimeTrain = submitPolicyGroupDTO.getStartTimeTrain();
            //培训期间(结束时间)
            String endTimeTrain = submitPolicyGroupDTO.getEndTimeTrain();
            //产品代码
            String productCode = submitPolicyGroupDTO.getProductCode();
            //投保时间（非必录）
            String applyTime = submitPolicyGroupDTO.getApplyTime();
            //投保人类型
            String holderType = submitPolicyGroupDTO.getHolderType();
            //投保人手机号（团体非必录）
            String insuredPhone = submitPolicyGroupDTO.getInsuredPhone();
            //证件类型
            String idType = submitPolicyGroupDTO.getIdType();
            //被保人证件号
            String startTime = submitPolicyGroupDTO.getStartTime();
            //证件有效期起期（非必录）
            String endTime = submitPolicyGroupDTO.getEndTime();
            //投保人职业/行业
            String insuredProfession = submitPolicyGroupDTO.getInsuredProfession();
            //投保人与被保人关系
            String insuredHolder = submitPolicyGroupDTO.getInsuredHolder();
            //被保人证件类型
            String insuredIdType = submitPolicyGroupDTO.getInsuredIdType();
            //证件有效期起期（非必录）
            String insuredStartTime = submitPolicyGroupDTO.getInsuredStartTime();
            //证件有效期止期（非必录）
            String insuredEndTime = submitPolicyGroupDTO.getInsuredEndTime();
            //被保险人职业/行业
            String insuredRelation = submitPolicyGroupDTO.getInsuredRelation();
            //保险起期#
            String effectiveStartTime = submitPolicyGroupDTO.getEffectiveStartTime();
            //教育机构证件类型
            String mechanismIdType = submitPolicyGroupDTO.getMechanismIdType();
            //学员是否成年
            String isAdult = submitPolicyGroupDTO.getIsAdult();
            //学员证件类型（非必录）
            String studentIdType = submitPolicyGroupDTO.getStudentIdType();
            //学员证件号码（非必录）
            String studentNo = submitPolicyGroupDTO.getStudentNo();
            //教育学习形式
            String educationMode = submitPolicyGroupDTO.getEducationMode();
            //接受增值服务的方式
            String addValueMode = submitPolicyGroupDTO.getAddValueMode();
            //课程表文件地址集合（多个地址间用英文;分割）
            String courseAddressList = submitPolicyGroupDTO.getCourseAddressList();
            //出单类型#
            String insureType = submitPolicyGroupDTO.getInsureType();
            //终保日期#
            String effectiveEndTime = submitPolicyGroupDTO.getEffectiveEndTime();
            if(StrUtil.isNotEmpty(orderId) && StrUtil.isNotEmpty(insuredName) && StrUtil.isNotEmpty(cid) && StrUtil.isNotEmpty(holderName)
            && StrUtil.isNotEmpty(insureType) && StrUtil.isNotEmpty(effectiveStartTime) && StrUtil.isNotEmpty(effectiveEndTime)
            && StrUtil.isNotEmpty(premium) && StrUtil.isNotEmpty(totalPremium) && StrUtil.isNotEmpty(reality)){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                //写入user表中到数据(Insured)被保人
                UserInsureEntity insuredUser = new UserInsureEntity();
                int userInsure = userInsureMapper.selectCount(new LambdaQueryWrapper<UserInsureEntity>().eq(UserInsureEntity::getPhone,insuredUser.getPhone()));
                if (userInsure > 0){
                    log.info("当前用户Cid已经存在！");
                }else {
                    insuredUser.setId(IdUtil.simpleUUID());
                    insuredUser.setName(holderName);
                    insuredUser.setPhone(holderPhone);
                    insuredUser.setCid(cid);
                    insuredUser.setStartTime(sdf.parse(startTime));
                    insuredUser.setEndTime(sdf.parse(endTime));
                    insuredUser.setCreateTime(new DateTime());
                    userInsureMapper.insert(insuredUser);
                }

                //投保人（团险）可为空
                UserInsureEntity holderUser = new UserInsureEntity();
                int holderCount = userInsureMapper.selectCount(new LambdaQueryWrapper<UserInsureEntity>().eq(UserInsureEntity::getPhone,holderUser.getPhone()));
                if(holderCount > 0){
                    log.info("当前用户Cid已经存在！");
                }else {
                    holderUser.setId(IdUtil.simpleUUID());
                    holderUser.setPhone(holderPhone);
                    holderUser.setName(holderName);
                    holderUser.setCid(cid);
                    holderUser.setStartTime(sdf.parse(startTime));
                    holderUser.setEndTime(sdf.parse(endTime));
                    holderUser.setCreateTime(new DateTime());
                    userInsureMapper.insert(holderUser);
                }
                //学生信息
                StudentEntity studentEntity = new StudentEntity();
                studentEntity.setId(IdUtil.simpleUUID());
                studentEntity.setStudentName(studentName);
                studentEntity.setStartTimeTrain(sdf.parse(startTimeTrain));
                studentEntity.setEndTimeTrain(sdf.parse(endTimeTrain));
                //教育学习形式 1:线上 2：线下
                studentEntity.setLearningModality(educationMode);
                //学生类型：0，成年1，未成年
                studentEntity.setStudentType(Integer.valueOf(studentIdType));
                studentEntity.setStudentIdNo(studentNo);
                studentEntity.setStudentIdType(studentIdType);
                studentEntity.setCreateTime(new DateTime());
                studentMapper.insert(studentEntity);
                //写入订单表中到数据
                PolicyOrderEntity policyOrderEntity = new PolicyOrderEntity();
                policyOrderEntity.setId(IdUtil.simpleUUID());
                policyOrderEntity.setOrderId(orderId);
                policyOrderEntity.setTotalPremium(premium);
                policyOrderEntity.setTotalAmount(totalPremium);
                //policyOrderEntity.setReality(reality);
                policyOrderEntity.setProductCode(productCode);

                MechanismEntity mechanismEntity = mechanismMapper.selectOne(new LambdaQueryWrapper<MechanismEntity>().eq(MechanismEntity::getBusinessLicens,businessLicens));
                //课程信息
                List<CourseEntity> courseEntity = courseMapper.selectList(new LambdaQueryWrapper<CourseEntity>().eq(CourseEntity::getMechanismId,mechanismEntity.getId()));
                //将字符转换成日期
                policyOrderEntity.setApplyTime(sdf.parse(applyTime));
                policyOrderEntity.setHolderType(holderType);
                policyOrderEntity.setInsuredProfession(insuredProfession);
                policyOrderEntity.setInsuredHolder(Integer.valueOf(insuredHolder));
                policyOrderEntity.setInsuredRelation(insuredRelation);
                policyOrderEntity.setEffectiveStartTime(sdf.parse(effectiveStartTime));
                policyOrderEntity.setEffectiveEndTime(sdf.parse(effectiveEndTime));
                policyOrderEntity.setInsureType(insureType);
                //将投保人id插入到订单表中
                policyOrderEntity.setInsuredPersonId(insuredUser.getId());
                policyOrderEntity.setHolderPersonId(holderUser.getId());
                //通过营业执照来获取机构信息(!!!)
                policyOrderEntity.setMechanismId(mechanismEntity.getBusinessLicens());
                policyOrderEntity.setCreateTime(new DateTime());
                policyOrderMapper.insert(policyOrderEntity);
            }else{
                log.info("必填字段不能为空，请填入后再提交！！");
                apiResult.setSuccess(false);
                apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
                apiResult.setMessage("必填字段不能为空");
            }
        }catch (Exception e){
            apiResult.setSuccess(false);
            apiResult.setCode(ResultCodeEnum.FAILURE.getCode());
            apiResult.setMessage("团险保险入库信息失败！！");
        }
        return apiResult;
    }
}
